<template>
 <span>
    <el-dialog
      :visible.sync="visible"
      :width="dialogWidth"
      center
      title="自动生成文章"
      :z-index="100004"
      modal-append-to-body
      :close-on-click-modal="false"
      class="bg-white rounded-xl shadow-2xl transform transition-all duration-300"
    >
    <div class="flex-col">
      <el-form
        :model="itemObj"
        ref="queryForm"
        size="small"
        label-width="80px"
        class="space-y-4"
      >
        <el-form-item label="文章篇数" prop="title">
          <el-input
            v-model="itemObj.count"
            placeholder="请输入要生成的文章数"
            clearable
            class="w-full max-w-md"
          />
        </el-form-item>

        <el-form-item label="一篇多少个图" prop="totalImages">
          <el-input
            v-model="itemObj.totalImages"
            placeholder="请输入一篇多少个图"
            clearable
            class="w-full max-w-md"
          />
        </el-form-item>

        <el-form-item label="一行多少列" prop="cols">
          <el-input
            v-model="itemObj.cols"
            placeholder="请输入一行分多少列"
            clearable
            class="w-full max-w-md"
          />
        </el-form-item>

        <el-form-item label="标题(非必填)" prop="cols">
          <div class="flex-row gap-10">
            <el-input
              v-model="itemObj.title"
              placeholder="标题"
              clearable
            />
            <el-input
              v-model="itemObj.titleIndex"
              placeholder="标题下标"
              clearable
              class="width-150"
            />
          </div>
        </el-form-item>

        <el-form-item label="公众号(非必填)" prop="cols">
           <el-select v-model="itemObj.publicAccountId" placeholder="请选择公众号" style="width: 100%;">
            <el-option
              v-for="item in publicAccountList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="flex-row gap-10 flex-wrap" style="margin-top: 10px">
        <el-button type="primary" size="small" @click="addCrawlerLinkImg">选择素材库的图(可不选)</el-button>
        <el-button type="primary" size="small" @click="updateTemporaryImg">上传图片(可不选)</el-button>
      </div>
      <el-divider/>

      <div class="height-300 overflow-auto">
        <el-row :gutter="24" style="margin: 0;">
          <el-col :span="24"  :md="6" :lg="4" :xl="4" :xs="6" :sm="6"  v-for="(url, index) in itemObj.imgUrls" :key="index" style="padding: 6px;">
            <el-card class="thumbnail-card flex-col" style="height: 200px;">
              <template #header>
                <div class="flex-row">
                  <div class="flex-1"></div>
                  <div class="flex-row" style="gap: 10px">
                    <el-button type="text" text  @click="confirmDeleteImage(url, index)" style="color: red;"
                    >删除</el-button>
                  </div>
                </div>
              </template>
              <div class="fill-width-height flex-col flex-1 " style="min-height: 0;">
                <LazyLoadImage
                  class="image"
                  fit="contain"
                  :src="url"
                  :lazy="true"
                >
                </LazyLoadImage>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="flex justify-end space-x-3 pt-4 border-t border-gray-100" style="margin-top: 10px;">
        <el-button type="primary" @click="autoGenerateArticle">提交</el-button>
      </div>
    </div>
  </el-dialog>

   <MaterialLibManagement ref="materialLibManagementRef" :isShowConfirm="true" @confirm="configSelect"/>
 </span>
</template>

<script>
import { autoGenerateArticle, upload as uploadImage } from '@/api/imgManage/writeArticles'
import LazyLoadImage from '@/components/LazyLoadImage/index.vue'
import MaterialLibManagement from './materialLibManagement'
import { getPublicAccountList } from "@/api/imgManage/publicAccount";

export default {
  name: '',
  components: {
    LazyLoadImage,
    MaterialLibManagement
  },
  props: {},
  data() {
    return {
      visible: false,
      itemObj: {
        count: 1,
        totalImages: 6,
        cols: 3,
        imgUrls: [],
        titleIndex: null,
        title: '',
        publicAccountId: ''
      },
      publicAccountList: [],
      dialogWidth: '50%'
    }
  },
  computed: {},
  methods: {
    init(){
      this.visible = true
      this.itemObj = {
        count: 1,
        totalImages: 8,
        cols: 4,
        imgUrls: []
      }
    },
    isMobile () {
      return navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )
    },
    addCrawlerLinkImg() {
      this.$nextTick(() => {
        console.log('$refs',this.$refs)
        this.$refs.materialLibManagementRef?.init()
      })
    },
    updateTemporaryImg() {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.multiple = true

      // 监听文件选择事件
      input.onchange = async (e) => {
        const files = e.target.files
        this.$message({ type: 'success', message: `选择了 ${files.length}个文件` })
        if (!files.length) return

        this.$modal.loading("正在上传图片，请稍候...");

        try {
          for (const file of files) {
            const formData = new FormData()
            formData.append('file', file)
            if(this?.itemObj?.publicAccountId?.length > 0){
              formData.append('publicAccountId', this.itemObj.publicAccountId)
            }
            const res = await uploadImage(formData)
            if (res?.url) {
              const newUrl = res.url.startsWith('http') ? res.url : this.$config.urlFormat(res.url, false)
              this.itemObj.imgUrls.push(newUrl)
            } else {
              this.$message({
                type: 'warning',
                message: `文件 ${file.name} 上传失败`
              })
            }
          }
          // 所有文件上传完成
          this.$message({
            type: 'success',
            message: `成功上传 ${this.itemObj.imgUrls.length} 张图片`
          })
        } catch (error) {
          // 上传过程中发生错误
          console.error('图片上传错误:', error)
          this.$message({
            type: 'error',
            message: '图片上传失败，请重试'
          })
          this.$modal.closeLoading()
        } finally {
          // 关闭加载提示
          this.$modal.closeLoading()
        }
      }
      // 触发文件选择对话框
      input.click()
    },
    configSelect(selectData) {
      const data = selectData || [];
      const newImgUrls = data.map(item => item.url);
      this.itemObj.imgUrls = [...new Set([
        ...this.itemObj.imgUrls,
        ...newImgUrls
      ])];
      this.$message({
        type: 'success',
        message: `已成功选择 ${this.itemObj.imgUrls.length} 张图片`
      })
    },
    // 确认删除图片
    confirmDeleteImage(url, index) {
      this.$confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteImage(url, index)
      }).catch(() => {
        // 取消操作，无需处理
      })
    },
    deleteImage(url, index) {
      this.itemObj.imgUrls.splice(index, 1)
      this.$message({
        type: 'success',
        message: '图片已删除'
      })
    },
    async autoGenerateArticle(){
      this.$modal.loading("正在生成中，请稍候...");
      const res = await autoGenerateArticle(this.itemObj).catch(e => {
        this.$modal.closeLoading()
      })
      if(res.code == 200){
        this.$message({
          type: 'success',
          message: '生成完成'
        })
        this.visible = false
        this.$emit('callBack')
      } else {
        this.$message({
          type: 'error',
          message: '生成错误'
        })
      }
      this.$modal.closeLoading()
    },
    async getPublicAccountList(){
      const res = await getPublicAccountList()
      this.publicAccountList =  res.data
    },
  },
  async mounted() {
    await this.getPublicAccountList()
    if(this.isMobile()){
      this.dialogWidth = '90%'
    }
  }
}
</script>


<style scoped lang="scss">

</style>
